<?php
session_start();

class home extends MY_Controller{
	private $status = true;
	
	function __construct(){
		parent::__construct();
		
		//CSS y JS Base
		$this->carabiner->css(array(
		    array('dev/style.css', 'screen', 'style.css')
		));
		$this->carabiner->js(array(
			array('dev/libs/jquery.js', 'screen', 'jquery.min.js'),
			array('dev/libs/jquery.autocomplete.js', 'screen', 'jquery.autocomplete.js'),
			array('dev/libs/jquery.lazyload.js', 'screen', 'jquery.lazyload.js'),
			array('dev/libs/jquery.toplink.js', 'screen', 'jquery.toplink.js'),
			array('dev/general.js', 'screen', 'general.js')
		));
	}
	
	public function _remap($method){
		//informacion del usaurio logeado
		$this->params['oauth_token'] = Sys::getTokenVal();
		if($this->params['oauth_token'] != FALSE){
			$this->load->model('user_model');
			$info = $this->user_model->getInfoUser($this->params);
			$this->params['usr_info'] = $info['user'];
		}
		
		if(isset($_COOKIE["p_goto"])){ //redireccionar a alguna url despues de logearse
			$url = $_COOKIE["p_goto"];
			setcookie('p_goto', '', time()-1200, '/');
			header("Location: ".$url);
		}else if($method=="index"){
	    	$this->phome();
		}else
	    	$this->{$method}();
	}
	
	
	/**
	 * Muestra las publicaciones mas recientes de peliculas, series, categorias o todas
	 */
	protected function phome(){
		$this->load->library('pagination');
		
		//Contenido de la barra derecha
		$this->asideBar();
		
		//Publicaciones
		$good = false;
		$this->publicationConfig();
		$publication = $this->publication_model->getPublications($this->params);
		if(is_array($publication['publications'])){
			$this->params['publication'] = $publication;
			$good = count($publication['publications'])>0? true: false;
		}
				
		$this->load->view("interface/header", $this->params);
		if($good)
			$this->load->view("interface/skin/publications", $this->params);
		else{
			$this->params['msg'] = lang('v_no_results');
			$this->params['seo']['description'] = $this->params['msg'];
			$this->load->view("interface/errors/page_error", $this->params);
		}
		$this->load->view("interface/aside", $this->params);
		$this->load->view("interface/footer", $this->params);
	}
	
	/**
	 * Muestra una pelicula con toda su informacion, online, descargas, trailer, etc
	 */
	public function film(){
		$this->params['id_film'] = $this->subSegment(1);
		
		//Contenido de la barra derecha
		$this->asideBar();
			
		$response_errors = $this->validate('getFilm');
		if($this->status == true){
			$this->load->model('films_model');
			
			
			$film = $this->films_model->getInfoFilm($this->params);
			if(is_array($film[0]))
				$this->params['film'] = $film[0];
			
			//segmento para el menu de peliculas
			$this->params['sub_segment'] = $this->subSegment(3);
			
			//configura parametros y lo que mostrara en la vista
			if(isset($this->params['film'])){
				$this->params['lang_m'] 		= $this->params['lang_url']!=''? substr($this->params['lang_url'], 0, 2): 'es';
				$this->params['url_article'] 	= urlencode(base_url($this->params['lang_url'].'films~'.$this->params['film']['id_film'].'~'.$this->params['film']['clean_title']));
				
				$options = array(
					'online' 	=> '', 
					'download' 	=> '~descargar',
					'capturs'	=> '~captura',
					'trailer'	=> '~trailer');
				$this->params['title'] = Sys::$title_web;
				foreach ($options as $key => $value) {
					if('~'.$this->params['sub_segment'] == $value || ($value == '' && $this->params['sub_segment'] == '')){
						$options[$key] 			= array(' class="sel-extra corner-all8"><h2>', '</h2>');
						$this->params['title']	= lang('v_'.$key).' '.$this->params['film']['title'].' ['.$this->params['film']['format_film'].']';
						$this->params['opc_selected']	= $key;
					}else
						$options[$key] = array('><a href="'.urldecode($this->params['url_article']).$value.'">', '</a>');
				}
				
				$this->params['options'] = $options;
			}
			
			$this->params['seo'] = array(
				'title' 		=> $this->params['title'].' - '.Sys::$title_web,
				'description' 	=> $this->params['title'].' Megaupload, Mediafire'
			);
			 
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/skin/film", $this->params);
			$this->load->view("interface/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}else{
			$this->params['msg'] = implode(',', $response_errors);
			$this->params['seo'] = array(
				'title' 		=> ''.Sys::$title_web,
				'description' 	=> $this->params['msg']
			);
			
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/errors/page_error", $this->params);
			$this->load->view("interface/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}
	}
	
	/**
	 * Muestra un episodio de una serie con su informacion, descarga, online, etc.
	 */
	public function serie_episode(){
		$this->params['episode'] = $this->subSegment(1);
		
		//Contenido de la barra derecha
		$this->asideBar();
			
		$response_errors = $this->validate('getEpisode');
		if($this->status == true){
			$this->load->model('series_model');
			
			
			$episode = $this->series_model->getEpisode($this->params);
			if(is_array($episode))
				$this->params['episode'] = $episode;
			
			$this->params['season'] = $episode['id_season'];
			$season = $this->series_model->getSeason($this->params);
			if(is_array($season))
				$this->params['season'] = $season;
			
			//segmento para el menu de peliculas
			$this->params['sub_segment'] = $this->subSegment(4);
			
			//configura parametros y lo que mostrara en la vista
			if(isset($this->params['episode'])){
				$this->params['lang_m'] 		= $this->params['lang_url']!=''? substr($this->params['lang_url'], 0, 2): 'es';
				$this->params['url_article'] 	= urlencode(base_url($this->params['lang_url'].'series~'.
													$this->params['episode']['id_episode'].'~'.$this->params['episode']['clean_title_serie'].
													'~'.$this->params['episode']['clean_title_episode']));
				
				$options = array(
					'online' 	=> '', 
					'download' 	=> '~descargar',
					'capturs'	=> '~captura',
					'trailer'	=> '~trailer');
				$this->params['title'] = Sys::$title_web;
				foreach ($options as $key => $value) {
					if('~'.$this->params['sub_segment'] == $value || ($value == '' && $this->params['sub_segment'] == '')){
						$options[$key] 			= array(' class="sel-extra corner-all8"><h2>', '</h2>');
						$this->params['title']	= lang('v_'.$key).' '.$this->params['episode']['title_serie'].
													' '.lang('v_season').' '.$this->params['episode']['no_season'].': '.
													lang('v_episode').' '.$this->params['episode']['no_episode'].' - '.$this->params['episode']['title_episode'].
													' ['.$this->params['episode']['format_episode'].']';
						$this->params['opc_selected']	= $key;
					}else
						$options[$key] = array('><a href="'.urldecode($this->params['url_article']).$value.'">', '</a>');
				}
				
				$this->params['options'] = $options;
			}
			
			$this->params['seo'] = array(
				'title' 		=> $this->params['title'].' - '.Sys::$title_web,
				'description' 	=> 'Serie '.$this->params['episode']['title_serie'].', '.$this->params['title'].' Megaupload, Mediafire'
			);
			 
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/skin/serie-episode", $this->params);
			$this->load->view("interface/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}else{
			$this->params['msg'] = implode(',', $response_errors);
			$this->params['seo'] = array(
				'title' 		=> ''.Sys::$title_web,
				'description' 	=> $this->params['msg']
			);
			
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/errors/page_error", $this->params);
			$this->load->view("interface/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}
	}

	/**
	 * Muestra la informacion de una temporada, episodios, otras temporadas, etc.
	 */
	public function serie_season(){
		$this->params['season'] = $this->subSegment(1);
		
		//Contenido de la barra derecha
		$this->asideBar();
			
		$response_errors = $this->validate('getSeason');
		if($this->status == true){
			$this->load->model('series_model');
			
			
			$season = $this->series_model->getSeason($this->params);
			if(is_array($season))
				$this->params['season'] = $season;
			
			$this->params['lang_m'] = $this->params['lang_url']!=''? substr($this->params['lang_url'], 0, 2): 'es';
			
			//segmento para el menu de peliculas
			$this->params['sub_segment'] = $this->subSegment(4);
			
			$title = $season['title_serie'].' '.lang('v_season').' '.$season['no_season'];
			$this->params['seo'] = array(
				'title' 		=> $title.' - '.Sys::$title_web,
				'description' 	=> lang('v_series_active').' '.$title,
				'title2'		=> $title
			);
			 
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/skin/serie-season", $this->params);
			$this->load->view("interface/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}else{
			$this->params['msg'] = implode(',', $response_errors);
			$this->params['seo'] = array(
				'title' 		=> ''.Sys::$title_web,
				'description' 	=> $this->params['msg']
			);
			
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/errors/page_error", $this->params);
			$this->load->view("interface/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}
	}

	public function actors(){
		$this->params['actor'] = $this->subSegment(1);
		
		//Contenido de la barra derecha
		$this->asideBar();
			
		$response_errors = $this->validate('actors');
		if($this->status == true){
			$this->load->library('pagination');
			
			
			//Publicaciones
			$good = false;
			$this->publicationConfig();
			$publication = $this->publication_model->getPublications($this->params);
			if(is_array($publication['publications'])){
				$this->params['publication'] = $publication;
				$good = count($publication['publications'])>0? true: false;
			}
			
			$actor = $this->publication_model->getInfoActor($this->params);
			$this->params['actor'] = $actor;
			
			$this->params['seo'] = array(
				'title' 		=> lang('seot_home_actor', $actor['name']).' - '.Sys::$title_web,
				'description' 	=> lang('seod_home_actor', $actor['name']),
				'title2'		=> lang('title_filmograpy', $actor['name'])
			);
			
			$this->load->view("interface/header", $this->params);
			if($good)
				$this->load->view("interface/skin/publications", $this->params);
			else{
				$this->params['msg'] = lang('v_no_results');
				$this->params['seo']['description'] = $this->params['msg'];
				$this->load->view("interface/errors/page_error", $this->params);
			}
		}else{
			$this->params['msg'] = implode(',', $response_errors);
			$this->params['seo'] = array(
				'title' 		=> ''.Sys::$title_web,
				'description' 	=> $this->params['msg']
			);
			
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/errors/page_error", $this->params);
		}
		$this->load->view("interface/aside", $this->params);
		$this->load->view("interface/footer", $this->params);
	}
	
	/**
	 * Registro de usuarios
	 */
	public function create_account(){
		//Contenido de la barra derecha
		$this->asideBar();
		
		
		$this->params['seo'] = array(
			'title' 		=> lang('v_create_account').' - '.Sys::$title_web,
			'title2' 		=> lang('v_create_account'),
			'description' 	=> ''
		);
		
		if(isset($this->params['register'])){
			$response_errors = $this->validate('create_account');
			if($this->status == true){
				$this->load->model('user_model');
				$res_save = $this->user_model->saveInfoUser($this->params);
				
				if($res_save == FALSE){
					//el usuario ya existe
					$this->params['msg'] = lang('exp_user_already_exists');
					$this->params['seo']['description'] = $this->params['msg'];
					$view = 'errors/page_error';
				}else{
					$url = $this->config->item('base_url').'services/oauth/register_user?consumer_key='.
						Sys::$consumer_key.'&user_id='.$res_save.'&consumer_secret='.Sys::$consumer_secret.
						'&is_login=yes';
					header("Location: ".$url);
					exit;
				}
			}else{
				//Ocurrio algun error
				$this->params['msg'] = implode(',', $response_errors);
				$this->params['seo']['description'] = $this->params['msg'];
				$view = 'errors/page_error';
			}
		}else{
			//formulario de registro
			$view = 'skin/create_account';
		}
		
		
		$this->load->view("interface/header", $this->params);
		$this->load->view("interface/".$view, $this->params);
		$this->load->view("interface/aside", $this->params);
		$this->load->view("interface/footer", $this->params);	
		
	}
	
	
	/**
	 * Carga los datos de la barra derecha para que la vista las procese
	 */
	private function asideBar(){
		$this->load->model('publication_model');
		$this->load->model('series_active_model');
		$this->load->model('category_model');
		
		//Proximos estrenos
		$publication = $this->publication_model->getComingSoon($this->params);
		$this->params['coming_soon'] = $publication;
				
		//Series activas
		$this->params['series_active'] = array();
		$publication = $this->series_active_model->getSerieActive($this->params);
		if(is_array($publication))
			$this->params['series_active'] = $publication['series_active'];
		
		//Lista de categorias
		$category = $this->category_model->get($this->params);
		$this->params['categories'] = $category['categories'];
	}
	
	/**
	 * Configura los parametros para ver las publicaciones
	 */
	private function publicationConfig(){
		$this->params['result_items_per_page'] 	= 40;
		$this->params['result_page'] 			= 0;
		if(isset($this->params['pag'])){
			if($this->params['pag'] % $this->params['result_items_per_page'] == 0)
				$this->params['result_page'] = ($this->params['pag']/$this->params['result_items_per_page']);
		}
		
		$this->params['seo'] = array(
			'title' 		=> '',
			'description' 	=> '',
			'title2'		=> ''
		);
		if($this->uri->segment($this->uri->total_segments()) !== FALSE){
			$sub_seg = explode('~', $this->uri->segment($this->uri->total_segments()));
			switch ($sub_seg[0]) {
				case 'films':
					$this->params['seo'] = array(
						'title' 		=> lang('seot_home_film', '').' - '.Sys::$title_web,
						'description' 	=> lang('seod_home_film', ''),
						'title2'		=> lang('v_publications_o', lang('v_films'), '')
					);
					
					$this->params['list'] = 'film';
					if(isset($sub_seg[1])){
						if(is_numeric($sub_seg[1])){
							$this->params['genre'] = $sub_seg[1];
							
							//Obtenemos la info de la categoria
							//$this->load->model('category_model');
							$categor = $this->category_model->get($this->params);
							$this->params['seo']['title'] 		= lang('seot_home_film', ' '.$categor['categories'][0]['name']).' - '.Sys::$title_web;
							$this->params['seo']['description'] = lang('seod_home_film', ' '.$categor['categories'][0]['name']);
							$this->params['seo']['title2'] = lang('v_publications_o', lang('v_films'), ' => '.$categor['categories'][0]['name']);
						}
					}
				break;
				case 'series':
					$this->params['seo'] = array(
						'title' 		=> lang('seot_home_serie', '').' - '.Sys::$title_web,
						'description' 	=> lang('seod_home_serie', ''),
						'title2'		=> lang('v_publications_o', lang('v_series'), '')
					);
					
					$this->params['list'] = 'serie';
					if(isset($sub_seg[1])){
						if(is_numeric($sub_seg[1])){
							$this->params['genre'] = $sub_seg[1];
							
							//Obtenemos la info de la categoria
							//$this->load->model('category_model');
							$categor = $this->category_model->get($this->params);
							$this->params['seo']['title'] 		= lang('seot_home_serie', ' '.$categor['categories'][0]['name']).' - '.Sys::$title_web;
							$this->params['seo']['description'] = lang('seod_home_serie', ' '.$categor['categories'][0]['name']);
							$this->params['seo']['title2']		= lang('v_publications_o', lang('v_series'), ' => '.$categor['categories'][0]['name']);
						}
					}
				break;
				case 'actors':
					if(isset($sub_seg[1]))
						$this->params['actor'] = $sub_seg[1];
				break;
				default:  //Cualquier categoria
					if(is_numeric($sub_seg[0])){
						$this->params['genre'] = $sub_seg[0];
						
						//Obtenemos la info de la categoria
						//$this->load->model('category_model');
						$categor = $this->category_model->get($this->params);
						
						$this->params['seo'] = array(
							'title' 		=> lang('seot_home', ' '.$categor['categories'][0]['name']).' - '.Sys::$title_web,
							'description' 	=> lang('seod_home', ' '.$categor['categories'][0]['name']),
							'title2'		=> lang('v_publications', ' => '.$categor['categories'][0]['name'])
						);
					}
				break;
			}
		}else{ //Configuracion del home
			//CSS y JS Base
			$this->carabiner->css(array(
			    array('dev/libs/nivo-slider.css', 'screen', 'nivo-slider.css')
			));
			$this->carabiner->js(array(
				array('dev/libs/jquery.nivo.slider.js', 'screen', 'jquery.nivo.slider.js')
			));
			$this->load->model('banner_model');
			
			$this->params['type'] = 'active';
			$banners = $this->banner_model->get($this->params);
			if(count($banners['banners']) > 0)
				$this->params['banners'] = $banners['banners'];
			
			$this->params['seo'] = array(
				'title' 		=> lang('seot_home', '').' - '.Sys::$title_web,
				'description' 	=> lang('seod_home', ''),
				'title2'		=> lang('v_publications', '')
			);
		}
	}
	
	
	
	/**
     * Permite incorporar las validaciones bases que apliquen para todos los servicios.
     * Validaciones mas espesificas tendran que ser en cada servicio en particular.
     * @author gama
     */
    protected function validate($val_method){
    	if(method_exists($this, 'validate_'.$val_method)){
    		$this->load->library('MY_Form_validation');
    		return $this->{'validate_'.$val_method}();
    	}
    }
	protected function validate_getFilm(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate($this->params);
    	
    	$validate->set_rules(array(
    			array(
    				'field' => 'id_film',
					'label' => 'id_film',
					'rules' => 'required|is_natural_no_zero')
    	));
    	$this->status = $validate->run();
    	return $validate->_error_array;
    }
	protected function validate_getEpisode(){
		$validate = new MY_Form_validation();
    	$validate->setArrayValidate($this->params);
    	
    	$validate->set_rules(array(
    			array(
    				'field' => 'episode',
					'label' => 'episode',
					'rules' => 'required|is_natural_no_zero')
    	));
    	$this->status = $validate->run();
    	return $validate->_error_array;
	}
	protected function validate_getSeason(){
		$validate = new MY_Form_validation();
    	$validate->setArrayValidate($this->params);
    	
    	$validate->set_rules(array(
    			array(
    				'field' => 'season',
					'label' => 'season',
					'rules' => 'required|is_natural_no_zero')
    	));
    	$this->status = $validate->run();
    	return $validate->_error_array;
	}
	protected function validate_actors(){
		$validate = new MY_Form_validation();
    	$validate->setArrayValidate($this->params);
    	
    	$validate->set_rules(array(
    			array(
    				'field' => 'actor',
					'label' => 'actor',
					'rules' => 'required|is_natural_no_zero')
    	));
    	$this->status = $validate->run();
    	return $validate->_error_array;
	}
	private function validate_create_account(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate($this->params);
    	
    	$validate->set_rules(array(
    			array('field' => 'name', 
                     'label' => 'name', 
                     'rules' => 'required|max_length[50]'),
    			array('field' => 'email', 
                     'label' => 'email', 
                     'rules' => 'required|valid_email|max_length[70]'),
    			array('field' => 'password', 
                     'label' => 'password', 
                     'rules' => 'required|min_length[6]|max_length[32]'),
    			array('field' => 'confirm_password', 
                     'label' => 'confirm_password', 
                     'rules' => 'max_length[32]'),
                     
				array('field' => 'user', 
                     'label' => 'user', 
                     'rules' => 'max_length[15]')
    	));
    	$this->status = $validate->run();
    	
    	if(isset($this->params["confirm_password"])){
    		if($this->params["confirm_password"] != $this->params["password"]){
    			$this->status = false;
    			$validate->_error_array['values'] = lang('txt_password_confirm');
    		}
    	}
    	
    	return $validate->_error_array;
    }
	
	
	
	/**
	 * Cambia el lenguaje de traduccion de la pagina
	 */
	public function changeLang(){
		$seg = $this->subSegment(1);
		setcookie('p_lang', '', time()-(3600*24*Sys::$destroy_session*23), '/');
		setcookie('p_lang', $seg, time()+(3600*24*Sys::$destroy_session*20), '/');
		
		if($seg == 'eng')
			header('Location: '.Sys::$url_base.'en/');
		else
			header('Location: '.Sys::$url_base);
	}
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * Carga el menu principal de la aplicacion
	 */
	function menu(){
		$response_errors = $this->validate('get');
		if($this->status == true){
			$this->load->model('user_model');
			
			$data = null;
			
			$params = array(
				"lang"=>					Sys::getLang(),
				"consumer_key"=>			Sys::$consumer_key,
				"consumer_secret"=>			Sys::$consumer_secret,
				'lmot4t'=>					$_SESSION['session']["lmot4t"],
				'lmot0n'=>					$_SESSION['session']["lmot0n"]
			);
				
			$params["title"] = Sys::$title_web;
			
			echo $this->load->view("interface/menu", $params, true);
		}else{
			/*$this->load->library('imageshack');
			$this->imageshack->upload(array(
				'file' => 'http://cinefolo.files.wordpress.com/2009/12/megan-fox-maxim-0112.jpg',
				'img_temp' => FALSE,
				'size' => array('big','medium','small')
			));
			echo $this->imageshack->getInfo('image_link', 'big')." - ".
				$this->imageshack->getInfo('thumb_link', 'big')."<br>";
			echo $this->imageshack->getInfo('image_link', 'medium')." - ".
				$this->imageshack->getInfo('thumb_link', 'medium')."<br>";
			echo $this->imageshack->getInfo('image_link', 'small')." - ".
				$this->imageshack->getInfo('thumb_link', 'small')."<br>";*/
			
			/*$this->load->library('UploadFiles');
			var_dump(
				$this->uploadfiles->uploadFile(array(
					'file' 		=> 'http://www.elmulticine.com/imagenes/artistas/megan-fox-b.jpg',
					'img_temp' 	=> FALSE,
					'size' 		=> array('big','medium','small')
				))
			);*/
			
			if(isset($_POST['enviar'])){
				$this->load->library('UploadFiles');
				var_dump(
					$this->uploadfiles->uploadFile(array(
						'file' 		=> 'img',
						'img_temp' 	=> TRUE,
						'size' 		=> array('big','medium','small')
					))
				);
			}
			
			
			echo $this->load->view("interface/errors/page_error", array(
				'msg' => implode(',', $response_errors),
				'title' => Sys::$title_web
			), true);
		}
	}
	
	function sessionError(){
		$params["title"] = Sys::$title_web;
		
		echo $this->load->view("interface/session_error", $params, true);
	}
	
	
	
	
	
	
	
	
	private function valSession(){
		$this->valSession = false;
		if(isset($_SESSION['session']['amot3s']{0})){
			if($_SESSION['session']['amot3s'] == Sys::$password_aes)
				$this->valSession = true;
		}
	}
	
	public function checkAccessToken(){
		$result = $this->config->item('store_oauth')->checkAccessToken(
					Sys::$consumer_key, 
					$this->token);
				
		if($result)
			return true;
		else 
			header("Location: ".$this->config->item('base_url')."services/user/logout?lang=".Sys::getLang());
	}
}
?>
